package com.common.util;

import java.io.*;
import java.nio.charset.Charset;

/**
 * Created by shihc on 2016/1/29.
 */
public class IoUtil {

    private final static int BUFFER_SIZE = 4096;

    /**
     * 将InputStream转换成String，默认采用utf8编码
     * @param in InputStream
     * @return String
     * @throws Exception
     *
     */
    public static String inputStreamToString(InputStream in) throws Exception {
        return inputStreamToString(in, Charsets.UTF8);
    }

    /**
     * 将InputStream转换成某种编码的String
     * @param in
     * @param charset
     * @return
     * @throws Exception
     */
    public static String inputStreamToString(InputStream in, Charset charset) throws Exception {
        byte[] bytes = inputStreamToByte(in);
        String returnStr = new String(bytes, charset);
        return returnStr;
    }

    /**
     * 将InputStream转换成byte数组
     * @param in InputStream
     * @return byte[]
     * @throws IOException
     */
    public static byte[] inputStreamToByte(InputStream in) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] data = new byte[BUFFER_SIZE];
        int count = -1;
        while ((count = in.read(data, 0, BUFFER_SIZE)) != -1){
            outStream.write(data, 0, count);
        }
        outStream.flush();
        byte[] bytes = outStream.toByteArray();
        outStream.close();
        return bytes;
    }

    /**
     * 将byte数组转换成String，默认采用utf8编码
     * @param bytes
     * @return
     * @throws Exception
     */
    public static String byteToString(byte[] bytes) throws Exception {
        return byteToString(bytes, Charsets.UTF8);
    }

    /**
     * 将byte数组转换成String，默认采用utf8编码
     * @param bytes
     * @return
     * @throws Exception
     */
    public static String byteToString(byte[] bytes, Charset charset) throws Exception {
        return new String(bytes, charset);
    }

    /**
     * 字符串转字节数组，默认采用utf8编码
     * @param string
     * @return
     * @throws UnsupportedEncodingException
     */
    public static byte[] stringToByte(String string) throws UnsupportedEncodingException {
        return stringToByte(string, Charsets.UTF8);
    }

    /**
     * 采用指定编码将字符串转换成字节数组
     * @param string
     * @param charset
     * @return
     * @throws UnsupportedEncodingException
     */
    public static byte[] stringToByte(String string, Charset charset) throws UnsupportedEncodingException {
        return string.getBytes(charset);
    }
}
